import Vue from 'vue'
import Vuex from 'vuex'
import { loginApi } from '@/api/user.js'
import { setToken, getToken, setUser, getUser, removeToken } from '@/utils/auth.js'

Vue.use(Vuex) // vue的插件机制

// Vuex.Store 构造器选项
const store = new Vuex.Store({
    // 为了不和页面或组件的data中的造成混淆，state中的变量前面建议加上$符号
    state: {
        // 用户信息
        userInfo: getUser() || {},
        token: getToken() || '',
        avatarUrl: getUser() ? getUser().icon : '',
    },
    mutations: {
        SET_TOKEN (state, token) {
            state.token = token
            setToken(token)
        },
        SET_USERINFO (state, userInfo) {
            state.userInfo = userInfo
            setUser(userInfo)
        },
        SET_AVATAR_URL (state, avatarUrl) {
            state.avatarUrl = avatarUrl
        },
        REMOVE_TOKEN (state) {
            state.token = null
            removeToken()
        },
    },
    actions: {
        login ({ commit }, userInfo) {
            return loginApi(userInfo).then(res => {
                commit('SET_TOKEN', res.data.token)
                commit('SET_USERINFO', res.data.userInfo)
                return  Promise.resolve(res)
            }).catch((err)=>{ return  Promise.reject(err)})
        }
    },
    getters: {
        isLogin: state => !!state.token,
        userInfo: state => state.userInfo,
        avatarUrl: state => state.avatarUrl  
    }
})

export default store
